from infoUi import wx
from infoUi import myInfoUi
from infoUi import threading
from myftp import MyFTP
from myftp import os
from mysftp import mySftp
class myNetUi(MyFTP,mySftp):

    def __init__(self, parent=None, title="MyTest",pos = (1000,680),size = (1024,600)):
        wx.Frame.__init__(self,parent=parent, title=title,size=size)
        self.panel = wx.Panel(self,size = (1024,600))

    def setUpNetUi(self):
        self.__ftpThread = threading.Thread()
        self.__sftpThread = threading.Thread()
        self.netUiCtr = {
            'host':'',
            'usr':'',
            'psw':'',
            'lPath':'',
            'rPath':'',
            'BoxSizer':''
        }
        #网络组件
        sNet_box = wx.StaticBox(self.panel, -1, "Net tool")
        self.netUiCtr['BoxSizer'] = wx.StaticBoxSizer(sNet_box,wx.VERTICAL)
        srvIp_box = wx.BoxSizer(wx.HORIZONTAL)
        usrName_box = wx.BoxSizer(wx.HORIZONTAL)
        password_box = wx.BoxSizer(wx.HORIZONTAL)
        lpath_box = wx.BoxSizer(wx.HORIZONTAL)
        rpath_box = wx.BoxSizer(wx.HORIZONTAL)
        srvBnt_box = wx.BoxSizer(wx.HORIZONTAL)

        #选项框
        netList = ['ftp', 'sftp']
        self.__netRbox = wx.RadioBox(self.panel, choices = netList,majorDimension = 1, style = wx.RA_SPECIFY_ROWS)

        #服务器地址
        srvIp_label = wx.StaticText(self.panel,label = "地址:",size=(60,-1))
        self.netUiCtr['host'] = wx.TextCtrl(self.panel,wx.ALIGN_LEFT,size=(-1,25),value=self.netConfig[0]['host'],style=wx.TE_PROCESS_ENTER)
        srvIp_box.Add(srvIp_label,proportion = 0)
        srvIp_box.Add(self.netUiCtr['host'],proportion = 1,flag=wx.ALL,border = 3)
        #用户名
        usrName_label = wx.StaticText(self.panel,label = "用户名:",size=(60,-1))
        self.netUiCtr['usr'] = wx.TextCtrl(self.panel,wx.ALIGN_LEFT,size=(-1,25),value=self.netConfig[0]['user'],style=wx.TE_PROCESS_ENTER)
        usrName_box.Add(usrName_label,proportion = 0)
        usrName_box.Add(self.netUiCtr['usr'],proportion = 1,flag=wx.ALL,border = 3)
        #密码
        password_label = wx.StaticText(self.panel,label = "密码:",size=(60,-1))
        self.netUiCtr['psw'] = wx.TextCtrl(self.panel,wx.ALIGN_LEFT,size=(-1,25),value=self.netConfig[0]['password'],style=wx.TE_PROCESS_ENTER)
        password_box.Add(password_label,proportion = 0)
        password_box.Add(self.netUiCtr['psw'],proportion = 1,flag=wx.ALL,border = 3)
        #本地路径
        lpath_label = wx.StaticText(self.panel,label = "近端路径:",size=(60,-1))
        self.netUiCtr['lPath'] = wx.TextCtrl(self.panel,wx.ALIGN_LEFT,size=(-1,25),value=self.netConfig[0]['localPath'],style=wx.TE_PROCESS_ENTER)
        lpath_box.Add(lpath_label,proportion = 0)
        lpath_box.Add(self.netUiCtr['lPath'],proportion = 1,flag=wx.ALL,border = 3)
        #远端路径
        rpath_label = wx.StaticText(self.panel,label = "远端路径:",size=(60,-1))
        self.netUiCtr['rPath'] = wx.TextCtrl(self.panel,wx.ALIGN_LEFT,size=(-1,25),value=self.netConfig[0]['remotePath'],style=wx.TE_PROCESS_ENTER)
        rpath_box.Add(rpath_label,proportion = 0)
        rpath_box.Add(self.netUiCtr['rPath'],proportion = 1,flag=wx.ALL,border = 3)
        #操作按钮
        srvBnt_put = wx.Button(self.panel,label = "上传")
        srvBnt_get = wx.Button(self.panel,label = "下载")
        srvBnt_box.Add(srvBnt_put,proportion = 1,flag=wx.ALL,border = 3)
        srvBnt_box.Add(srvBnt_get,proportion = 1,flag=wx.ALL,border = 3)

        #网络组件布局
        self.netUiCtr['BoxSizer'].Add(self.__netRbox,proportion = 0,flag=wx.EXPAND)
        self.netUiCtr['BoxSizer'].Add(srvIp_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.netUiCtr['BoxSizer'].Add(usrName_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.netUiCtr['BoxSizer'].Add(password_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.netUiCtr['BoxSizer'].Add(lpath_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.netUiCtr['BoxSizer'].Add(rpath_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.netUiCtr['BoxSizer'].Add(srvBnt_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)


        #事件绑定
        self.netUiCtr['host'].Bind(wx.EVT_TEXT_ENTER,self.__onEnterText)
        self.netUiCtr['usr'].Bind(wx.EVT_TEXT_ENTER,self.__onEnterText)
        self.netUiCtr['psw'].Bind(wx.EVT_TEXT_ENTER,self.__onEnterText)
        self.netUiCtr['lPath'].Bind(wx.EVT_TEXT_ENTER,self.__onEnterText)
        self.netUiCtr['rPath'].Bind(wx.EVT_TEXT_ENTER,self.__onEnterText)
        srvBnt_put.Bind(wx.EVT_BUTTON, self.onPutFile)
        srvBnt_get.Bind(wx.EVT_BUTTON, self.onGetFile)
        self.__netRbox.Bind(wx.EVT_RADIOBOX,self.__onNetRadioBox)

    def __savNetConf(self):
        if('sftp' in str(self.__netRbox.GetStringSelection())):
            save = 0 #保存ftp参数
        else:
            save = 1 #保存sftp参数
        #保存配置
        self.netConfig[save] = {
                "host": self.netUiCtr['host'].GetValue(),
                "user": self.netUiCtr['usr'].GetValue(),
                "password": self.netUiCtr['psw'].GetValue(),
                "localPath": self.netUiCtr['lPath'].GetValue(),
                "remotePath": self.netUiCtr['rPath'].GetValue()
            }

    def __displayNetConf(self):
        if('sftp' in str(self.__netRbox.GetStringSelection())):
            display = 1 #显示sftp参数
        else:
            display = 0 #显示ftp参数
        self.netUiCtr['host'].SetValue(self.netConfig[display]['host'])
        self.netUiCtr['usr'].SetValue(self.netConfig[display]['user'])
        self.netUiCtr['psw'].SetValue(self.netConfig[display]['password'])
        self.netUiCtr['lPath'].SetValue(self.netConfig[display]['localPath'])
        self.netUiCtr['rPath'].SetValue(self.netConfig[display]['remotePath'])

    def __onEnterText(self,evt):
        if('sftp' in str(self.__netRbox.GetStringSelection())):
            save = 1 #保存sftp参数
        else:
            save = 0 #保存sftp参数
        #保存配置,当前是什么就保存什么
        self.netConfig[save] = {
                "host": self.netUiCtr['host'].GetValue(),
                "user": self.netUiCtr['usr'].GetValue(),
                "password": self.netUiCtr['psw'].GetValue(),
                "localPath": self.netUiCtr['lPath'].GetValue(),
                "remotePath": self.netUiCtr['rPath'].GetValue()
            }

    def __onNetRadioBox(self, evt):
        self.__savNetConf()
        self.__displayNetConf()

    def __ftpOps(self,ops):
        #服务器地址或者域名
        tmp = str(self.netUiCtr['host'].GetValue()).split(':',1)
        host = str(tmp[0])
        port = 21
        if(len(tmp) > 1):
            port = int(tmp[1])
        #用户名
        usr=self.netUiCtr['usr'].GetValue()
        #密码
        psw=self.netUiCtr['psw'].GetValue()
        #本地路径
        lPath=self.netUiCtr['lPath'].GetValue()
        #远端路径
        rPath=self.netUiCtr['rPath'].GetValue()

        if(len(host) != 0 and len(usr) != 0 and len(psw) != 0):
            #ftp参数配置
            self.ftpInit(host,port)
            #登录
            self.login(usr,psw)
            if(ops):
                #上传文件
                self.upload_file_tree(lPath,rPath)
            else:
                #下载文件
                self.download_file(os.path.join(lPath,"new2old.bin"), rPath+"/new2old.bin")
                self.download_file(os.path.join(lPath,"old2new.bin"), rPath+"/old2new.bin")
            #关闭ftp client
            self.ftpClose()
        else:
            self.errorDebug("value not enough!\r\n")

    def __sftpOps(self,ops):
        #服务器地址或者域名
        tmp = str(self.netUiCtr['host'].GetValue()).split(':',1)
        host = str(tmp[0])
        port = 22
        if(len(tmp) > 1):
            port = int(tmp[1])
        #用户名
        usr=self.netUiCtr['usr'].GetValue()
        #密码
        psw=self.netUiCtr['psw'].GetValue()
        #本地路径
        lPath=self.netUiCtr['lPath'].GetValue()
        #远端路径
        rPath=self.netUiCtr['rPath'].GetValue()

        if(len(host) != 0 and len(usr) != 0 and len(psw) != 0):
            if(ops):
                self.sftpLogin(host,port,usr,psw)
                #上传文件
                for fname in os.listdir(lPath):
                     # 逐个检查指定目录
                    path = os.path.join(lPath, fname)
                    # 把文件名和所在目录名连接起来
                    if os.path.isfile(path):
                        # 判断是否是“文件”类型
                        fname_main, fname_ext = os.path.splitext(fname)
                        # 把文件名和后缀切分开
                        if fname_ext == ".bin" or fname_ext == '.bin_1' or fname_ext == '.bin_2':
                            self.sftpUpLoad(os.path.join(lPath,fname),os.path.join(rPath,fname).replace('\\','/'))
                self.sftpClose()
                pass
            else:
                self.sftpLogin(host,port,usr,psw)
                self.sftpDownLoad(os.path.join(lPath,"new2old.bin"),rPath+"/new2old.bin")
                self.sftpDownLoad(os.path.join(lPath,"old2new.bin"),rPath+"/old2new.bin")
                self.sftpClose()
                pass
            pass

    def __startFtpThread(self,ops):
        if(self.__ftpThread.is_alive() == False):
            self.__ftpThread = threading.Thread(target=self.__ftpOps, name='ftpNet', daemon=True,args=(ops,))
            self.__ftpThread.start()
        else:
            self.errorDebug("ftp service is run!\r\n")

    def __startSftpThread(self,ops):
        if(self.__sftpThread.is_alive() == False):
            self.__sftpThread = threading.Thread(target=self.__sftpOps, name='sftpNet', daemon=True,args=(ops,))
            self.__sftpThread.start()
        else:
            self.errorDebug("net service is run!\r\n")


    def onPutFile(self,evt):
        self.__onEnterText(evt)
        if('sftp' in self.__netRbox.GetStringSelection()):
            #上传文件
            self.__startSftpThread(1)
        else:
            self.__startFtpThread(1)


    def onGetFile(self,evt):
        self.__onEnterText(evt)
        if('sftp' in self.__netRbox.GetStringSelection()):
            #下载文件
            self.__startSftpThread(0)
        else:
            self.__startFtpThread(0)



#netUi demo
if __name__ == '__main__':
    app = wx.App()
    frame = myNetUi(title="While there is life,there is hope.")
    frame.setUpInfoUi()
    frame.setUpNetUi()
    mainBox = wx.BoxSizer()
    mainBox.Add(frame.infoUiCtr['BoxSizer'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)
    mainBox.Add(frame.netUiCtr['BoxSizer'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)
    frame.panel.SetSizer(mainBox)
    frame.Show()
    app.MainLoop()



